//服务器启动文件
//node server.js
//引入web框架
var express = require('express');
//引入以解析post
var bodyParser = require('body-parser');
//引入以解析cookie
var cookieParser = require('cookie-parser')
//引入以生成时间
var sdatetime = require('silly-datetime');
//引入数据库
var mysql = require('mysql');
//初始化框架
var app = express();
//初始化数据链接
var connection = mysql.createConnection({
    host: '118.244.234.107',
    user: 'wangwei',
    password: 'WangWei46',
    database:'wangwei'
});
//直接启动连接，后边一直不使用connection.end() 防止mysql中断引起进程挂掉
connection.connect();


//启用静态资源目录
app.use(express.static('public'));

//接受GET请求
app.get('/process_get', function (req, res) {
    // 输出 JSON 格式
    var response = {
        "first_name":req.query.first_name,
        "last_name":req.query.last_name
    };
    console.log(response);
    res.end(JSON.stringify(response));
})


//接受post参数
//注意事先加载bodyparse扩展
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/process_post', urlencodedParser, function (req, res) {
    // 输出 JSON 格式
    var response = {
        "first_name":req.body.first_name,
        "last_name":req.body.last_name
    };
    console.log(response);
    res.end(JSON.stringify(response));
})


//使用cookie
app.use(cookieParser());
app.get('/setcookie', function(req, res) {
    // 设置cookie
    res.cookie('name','myname',{
        path:'/',//访问哪一个路径的时候我们给你加上cookie
        maxAge:20*60*1000//cookie的存活时间,单位毫秒
    });
    res.send('ok');
})

app.get('/cookie', function(req, res) {
    //输出cookie
    res.send(req.cookies);
    console.log("Cookies: ", req.cookies);
})


app.get('/time', function(req, res) {
    var time=sdatetime.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
    console.log(time);
    res.send(time);
})


app.get('/list', function(req, res) {
        //查询
        // connection.connect();
        connection.query('select * from `music`', function(err, rows, fields) {
            if (err) {
                res.send("{\"total\": \"0\",\"data\": \"[]\",\"message\": \"出错了，你的参数是不是错了啊\"}");
            } else {
                var json=new Object()
                json.total=rows.length;
                json.data=rows;
                console.log('查询结果为: ', rows);
                res.send(json);
            }
        });
        //关闭连接
        // connection.end();

    })

app.get('/info', function(req, res) {
    // try {
        //查询
        var id = req.query.id;
        // connection.connect();
        connection.query('select * from `music` where id = '+id, function(err, rows, fields) {
            // if (err) throw err;
            if (err) {
                res.send("{\"status\": \"0\",\"message\": \"出错了，你的参数是不是错了啊\"}");
            } else {

                var json=new Object()
                json.status=1;
                json.message="获取成功";
                json.data=rows;
                res.send(json);
                console.log('查询结果为: ', rows);
            }
        });
        //关闭连接
        // connection.end();
    // } catch(e) {
    //     console.error('MYSQL出错了。你的sql不对：', e);
    // }
})




app.post('/edit', urlencodedParser, function (req, res) {
    var id = req.body.id;
    var title = req.body.title;
    var url = req.body.url;
    var img = req.body.img;
    var singer = req.body.singer;
    var type = req.body.type;
    var status = req.body.status;
    var created_time = sdatetime.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
    if (id !=0) {
        var sql = 'UPDATE `music` SET `title` = \''+title+'\' , `url` = \''+url+'\', `img` = \''+img+'\', `singer` = \''+singer+'\', `type` = '+type+', `status` = '+status+'  WHERE `id` = '+id;
        console.log(sql);

    }else{
        var sql = 'INSERT INTO `music` (`title`, `url`,`img`, `singer`, `type`, `status`, `created_time`) VALUES    (\''+title+'\', \''+url+'\', \''+img+'\',\''+singer+'\','+type+','+status+',\''+created_time+'\');';

    }

    try {
        // res.send(sql);

        // connection.connect();
        connection.query(sql, function(err, result) {
            if (err) throw err;
            console.log('查询结果为: ', result);
            res.send(result);
        });
        //关闭连接
        // connection.end();
        //
    } catch(e) {
        console.error('MYSQL出错了。你的sql不对：', e);
    }
})


//当出现意外的错误的时候，防止进程退出
// process.on('uncaughtException', function (err) {
//   console.log(err);
//   // res.send('服务器出错');
// });

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("应用实例，访问地址为 http://%s:%s", host, port)

})
